import { useCallback, useRef, useState } from 'react';

export const useSound = () => {
  const [isEnabled, setIsEnabled] = useState(true);
  const audioContextRef = useRef<AudioContext | null>(null);

  const initAudioContext = useCallback(() => {
    if (!audioContextRef.current) {
      const AudioContextClass = window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
      audioContextRef.current = new AudioContextClass();
    }
    return audioContextRef.current;
  }, []);

  const playBeep = useCallback((frequency: number, duration: number, volume = 0.3) => {
    if (!isEnabled) return;

    try {
      const audioContext = initAudioContext();
      const oscillator = audioContext.createOscillator();
      const gainNode = audioContext.createGain();

      oscillator.connect(gainNode);
      gainNode.connect(audioContext.destination);

      gainNode.gain.value = volume;
      oscillator.frequency.value = frequency;
      oscillator.type = 'sine';

      const currentTime = audioContext.currentTime;
      gainNode.gain.setValueAtTime(volume, currentTime);
      gainNode.gain.exponentialRampToValueAtTime(0.01, currentTime + duration);

      oscillator.start(currentTime);
      oscillator.stop(currentTime + duration);
    } catch (error) {
      console.warn('Audio playback failed:', error);
    }
  }, [isEnabled, initAudioContext]);

  const playSuccessSound = useCallback(() => {
    playBeep(523, 0.2, 0.3); // C5 音符
    setTimeout(() => playBeep(659, 0.2, 0.3), 100); // E5 音符
    setTimeout(() => playBeep(784, 0.3, 0.3), 200); // G5 音符
  }, [playBeep]);

  const playErrorSound = useCallback(() => {
    playBeep(220, 0.1, 0.2); // A3 音符
    setTimeout(() => playBeep(196, 0.3, 0.2), 100); // G3 音符
  }, [playBeep]);

  const playClickSound = useCallback(() => {
    playBeep(800, 0.1, 0.1);
  }, [playBeep]);

  const playLevelUpSound = useCallback(() => {
    const notes = [523, 659, 784, 1047]; // C5, E5, G5, C6
    notes.forEach((note, index) => {
      setTimeout(() => playBeep(note, 0.2, 0.3), index * 150);
    });
  }, [playBeep]);

  const playCelebrationSound = useCallback(() => {
    if (!isEnabled) return;

    // 庆祝音效 - 上升的旋律
    const celebrationMelody = [
      { note: 262, duration: 0.15, delay: 0 },    // C4
      { note: 330, duration: 0.15, delay: 150 },  // E4
      { note: 392, duration: 0.15, delay: 300 },  // G4
      { note: 523, duration: 0.15, delay: 450 },  // C5
      { note: 659, duration: 0.15, delay: 600 },  // E5
      { note: 784, duration: 0.15, delay: 750 },  // G5
      { note: 1047, duration: 0.3, delay: 900 },  // C6 (longer)
      // 第二段
      { note: 1047, duration: 0.1, delay: 1300 }, // C6
      { note: 1175, duration: 0.1, delay: 1400 }, // D6
      { note: 1319, duration: 0.1, delay: 1500 }, // E6
      { note: 1397, duration: 0.4, delay: 1600 }, // F6 (finale)
    ];

    celebrationMelody.forEach(({ note, duration, delay }) => {
      setTimeout(() => playBeep(note, duration, 0.4), delay);
    });

    // 添加一些装饰音效
    setTimeout(() => {
      [1319, 1175, 1047, 880].forEach((note, index) => {
        setTimeout(() => playBeep(note, 0.1, 0.2), index * 50);
      });
    }, 2200);
  }, [isEnabled, playBeep]);

  const toggleSound = useCallback(() => {
    setIsEnabled(!isEnabled);
  }, [isEnabled]);

  return {
    isEnabled,
    toggleSound,
    playSuccessSound,
    playErrorSound,
    playClickSound,
    playLevelUpSound,
    playCelebrationSound
  };
};